const adminDao = require('../dao/adminDao')
const roleDao = require('../dao/roleDao')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const config = require('../config/config.js')

// 测试
exports.test = async ctx => {
  let map = {
    username:123,
    password:123,
  }
  let res = await adminDao.test(map);
  ctx.body = {
    code:0,
    data:res
  }
}

// 用户登录
exports.login = async ctx => {
  let body = ctx.request.body
  let res = await adminDao.findByName(body);
  if(!res){
    ctx.body = {
      code: 1,
      message: '账号或密码错误',
    }
    return 
  }
  let { id,username,password} = res
  console.log(res)
  if (body.username === username && body.password === password) {
    let { shop_id } = await adminDao.findById(id)
    // 生成token
    let {
      secretKey,
      expiresIn
    } = config.security
    let payload = {
      id: id,
      username: username,
      shop_id:shop_id
    }
    let token = jwt.sign(payload, secretKey, {
      expiresIn: expiresIn
    });
    // 获取路由权限
    let roleId = await roleDao.getRole(id)
    let auth = []
    if(roleId){
      let rules = await roleDao.getRules({rid:roleId})
      rules.map(item => {
        auth.push(item.pid)
      })
    }
    let isAdmin = false
    if(id == 1){
      isAdmin = true
    }
    ctx.body = {
      code: 0,
      message: '登录成功',
      token,
      auth:auth,
      isAdmin:isAdmin
    }
  } else {
    ctx.body = {
      code: 1,
      message: '账号或密码错误',
    }
  }
}

// 创建账号
exports.create = async ctx => {
  let body = ctx.request.body
  // let token = ctx.request.headers["authorization"];
  // let payload = jwt.verify(token,config.security.secretKey)
  // body.above_id = payload.id
  const res = await adminDao.create(body);
  console.log(res)
  ctx.body = {
    code:0,
    message:'创建成功'
  }
}

// 获取所有账号(分页)
exports.getAllAdmin = async ctx =>{
  let { p = 1,limit = 10 } = ctx.request.query
  let offset = (p - 1) * limit;
  console.log(p,limit,offset)
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await adminDao.getAllAdmin(body);
  ctx.body = {
    code: 0,
    data: res
  }
}